/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextRequest, NextResponse } from 'next/server';
import { postAnswer } from '@/app/services/answer';

// 生成答案信息
function genAnswerInfo(reqBody: any) {
    const answerList: any[] = [];

    // 遍历请求体中的每一个键值对
    Object.keys(reqBody).forEach((key) => {
        // 如果键是questionId，则跳过
        if (key === "questionId") return;
        // 将键值对转换为答案信息，并添加到答案列表中
        answerList.push({
            componentId: key,
            value: reqBody[key]
        });
    });

    // 返回答案信息
    return {
        questionId: reqBody.questionId || "",
        answerList
    };
}

export async function POST(req: NextRequest) {

    // 获取请求体中的表单数据
    const formData = await req.formData();

    // 将表单数据转换为对象
    const body = Object.fromEntries(formData.entries());

    // 生成答案信息
    const answerInfo = genAnswerInfo(body);

    try {

        // 调用postAnswer方法，发送答案信息
        const resData = await postAnswer(answerInfo);

        console.log("resData:", resData);

        // 如果返回的数据errno为0，则跳转到成功页面
        if ((resData as any).errno === 0) {
            const url = new URL('/success', req.nextUrl.origin);
            return NextResponse.redirect(url);
            // 否则，跳转到失败页面，并将错误信息添加到URL中
        } else {
            const url = new URL('/fail', req.nextUrl.origin);
            url.searchParams.append("error", encodeURIComponent((resData as any).message || "Unknown error"));
            return NextResponse.redirect(url);
        }
        // 如果发生错误，则跳转到失败页面，并将错误信息添加到URL中
    } catch (error: any) {
        console.error('无法解析请求正文:', error);
        const url = new URL('/fail', req.nextUrl.origin);
        url.searchParams.append("error", encodeURIComponent(error.message || "Unknown error"));
        return NextResponse.redirect(url);
    }
}